﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using OpenQuarters.WebQuarters.Core;
using System.IO;
using OpenQuarters.WebQuarters.Utils;
using System.Web.Mvc;

namespace OpenQuarters.WebQuarters.Modules.Core
{
    public class ContentModule : Module
    {
        public static Dictionary<string, string> Templates
        {
            get
            {
                var d = new Dictionary<string, string>();
                d.Add("", "Default");
                foreach (var dir in new DirectoryInfo(Oracle.Context.Server.MapPath("~/Templates/")).GetDirectories())
                {
                    if (dir.Name.Contains(typeof(ContentModule).FullName))
                    {
                        foreach (var template in dir.GetFiles("*.ascx", SearchOption.TopDirectoryOnly))
                        {
                            d.Add(template.Name.Replace(".ascx", ""), template.Name.Replace(".ascx", ""));
                        }
                    }
                }
                return d;
            }
        }

        private string content = "<p>Default content</p>";

        [Newtonsoft.Json.JsonProperty]
        public string Content
        {
            get { return content; }
            set { content = value; }
        }

        private string template = "";

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.DropDown, OptionSource = "OpenQuarters.WebQuarters.Modules.Core.ContentModule.Templates")]
        public string Template
        {
            get { return template; }
            set { template = value; }
        }

        public ContentModule()
        {
        }

        public override void Initialise()
        {
            this.ModuleName = "Page Content";
            this.ModuleDescription = "Allows normal HTML content to be added to the page.";
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            JavaScript.RegisterScript("Modules.Content.AdminScript.js", "OpenQuarters.WebQuarters.Modules.Core", "Resources.Content.AdminScript.js", JavaScriptType.AdminScript);

            //TODO: Find out why gif images arent getting processed properly
            //this.Content = ParseImages(this.Content);

            if (this.Template.Length == 0)
            {
                this.Controls.Add(new LiteralControl(this.Content));
            }
            else
            {
                var viewPath = "~/Templates/" + this.GetType().FullName + "/" + this.Template + ".ascx";
                //this.Controls.AddLiteral(GeneralUtils.RenderViewToString(
                //        Oracle.CurrentControllerContext,
                //        viewPath,
                //        null,
                //        new ViewDataDictionary(this),
                //        new TempDataDictionary()));
                this.Controls.AddLiteral(GeneralUtils.RenderPartialToString(viewPath, this));
            }
        }

        public override string GetJQueryEditorName()
        {
            return "cmsModuleEditor, cmsContentModuleEditor";
        }

        private string ParseImages(string input)
        {
            //Parse local images to replace with the image handler
            Regex regex1 = new Regex(@"<img[^>]* src=\""(/Areas/CMS/Content/UserFiles[^\""]*)\""[^>]*>");
            foreach (Match match in regex1.Matches(input))
            {
                Regex widthRegex = new Regex(@"width:([^;]*)");
                Match widthMatch = widthRegex.Matches(match.Captures[0].Value)[0];
                string width = null;
                if (widthMatch != null)
                    width = widthMatch.Captures[0].Value.Split(':')[1];
                if (!string.IsNullOrEmpty(width))
                {
                    if (width.IndexOf("px") != -1)
                        width = width.Substring(0, width.IndexOf("px"));
                }
                else
                    width = "0";

                Regex heightRegex = new Regex(@"height:([^;]*)");
                Match heightMatch = heightRegex.Matches(match.Captures[0].Value)[0];
                string height = null;
                if (heightMatch != null)
                    height = heightMatch.Captures[0].Value.Split(':')[1];
                if (!string.IsNullOrEmpty(height))
                {
                    if (height.IndexOf("px") != -1)
                        height = height.Substring(0, height.IndexOf("px"));
                }
                else
                    height = "0";

                input = input.Replace(match.Captures[0].Value, match.Captures[0].Value.Replace("/Areas/CMS/Content/UserFiles", string.Format("/CMS/File/Image/{0}/{1}", width.Trim(), height.Trim())));
            }

            ////Parse image handler images and update dimensions
            Regex regex2 = new Regex(@"<img[^>]* src=\""(/CMS/File/Image[^\""]*)\""[^>]*>");
            foreach (Match match in regex2.Matches(input))
            {
                if (match.Captures.Count == 0)
                {
                    continue;
                }

                Regex widthRegex = new Regex(@"width:([^;]*)");
                var widthMatches = widthRegex.Matches(match.Captures[0].Value);
                Match widthMatch = widthMatches.Count > 0 ? widthMatches[0] : null;
                string width = null;
                if (widthMatch != null)
                {
                    width = widthMatch.Captures[0].Value.Split(':')[1];
                }
                if (!string.IsNullOrEmpty(width))
                {
                    if (width.IndexOf("px") != -1)
                    {
                        width = width.Substring(0, width.IndexOf("px"));
                    }
                }
                else
                {
                    width = "0";
                }

                Regex heightRegex = new Regex(@"height:([^;]*)");
                var heightMatches = heightRegex.Matches(match.Captures[0].Value);
                Match heightMatch = heightMatches.Count > 0 ? heightMatches[0] : null;
                string height = null;
                if (heightMatch != null)
                {
                    height = heightMatch.Captures[0].Value.Split(':')[1];
                }
                if (!string.IsNullOrEmpty(height))
                {
                    if (height.IndexOf("px") != -1)
                    {
                        height = height.Substring(0, height.IndexOf("px"));
                    }
                }
                else
                {
                    height = "0";
                }

                Regex updateDimensions = new Regex("/CMS/File/Image/([^/]*)/([^/]*)");
                input = input.Replace(match.Captures[0].Value, updateDimensions.Replace(match.Captures[0].Value, string.Format("/CMS/File/Image/{0}/{1}", width.Trim(), height.Trim())));
            }

            return input;
        }
    }
}